package com.dong.ui.view;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.dong.common.pojo.ResultVO;
import com.dong.common.util.RequestUtils;
import com.dong.common.view.CommonView;
import com.dong.module.foodmenu.pojo.FoodMenu;
import com.dong.module.menulog.pojo.MenuLog;
import com.dong.ui.component.CommonDialog;
import com.dong.ui.constant.RouterConst;
import com.dong.ui.util.ComponentUtils;
import com.dong.ui.util.ImageUtils;
import com.dong.ui.util.MessageUtils;
import com.dong.ui.util.RouterUtils;
import org.springframework.transaction.annotation.Transactional;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: 陈瑞东
 * @create: 2021-09-02 14:01
 */
public class FoodLogFrame extends CommonDialog implements CommonView {

    private JDialog jd = this;

    /*==================组件==================*/
    private static final int WIDTH = 1000;
    private static final int HEIGHT = 800;

    private static final int RIGHT_WIDTH = 700;

    private static final int TITLE_HEIGHT = 100;

    private static final int IMAGE_WIDTH = 400;
    private static final int IMAGE_HEIGHT = 400;

    private static final int DESC_HEIGHT = 200;

    private JPanel leftPanel;
    private JPanel rightPanel;
    private JSplitPane outSplitPane;

    private JPanel titleContainer;
    private JLabel title;

    private JPanel imageContainer;
    private JLabel image;

    private JScrollPane descContainer;
    private JTextArea description;

    private JScrollPane logListContainer;
    private JList<String> logList;

    private JButton addBtn;
    private JButton updateBtn;


    /*==================组件==================*/
    /*==================参数==================*/
    private String foodId;
    private FoodMenu foodMenu;
    private int count;
    private DefaultListModel<String> defaultListModel;

    private MenuLog menuLog;
    /*==================参数==================*/
    /*==================标志==================*/
    boolean requestFlag = true;

    /*==================标志==================*/

    @Override
    public void init(Map<String, Object> params) {
        // 设置标题
        setTitle("菜单日志");
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);

        initParams(params);
        initComponent();
        handleView();

        // 设置大小
        setSize(new Dimension(WIDTH, HEIGHT));
        // 设置不可改变大小
        setResizable(false);
        // 设置居中
        setLocationRelativeTo(null);
        // 在显示前处理，否则会被阻塞（模态框），无法加载事件
        handleAction();
        // 设置可见
        setVisible(true);
    }

    @Override
    public void initComponent() {
        Font titleFont = new Font("Stsong", Font.BOLD, 36);
        Font normalFont = new Font("Stsong", Font.PLAIN, 24);

        leftPanel = new JPanel();

        rightPanel = new JPanel(new BorderLayout());

        outSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel);
        outSplitPane.setEnabled(false);

        titleContainer = new JPanel(new GridLayout(1, 1, 0, 0));
        titleContainer.setPreferredSize(new Dimension(RIGHT_WIDTH, TITLE_HEIGHT));
        title = new JLabel(foodMenu.getName(), SwingConstants.CENTER);
        title.setFont(titleFont);

        imageContainer = new JPanel(new GridLayout(1, 1, 0, 0));
        imageContainer.setPreferredSize(new Dimension(RIGHT_WIDTH, IMAGE_HEIGHT));
        image = new JLabel(ImageUtils.scaleImage(new ImageIcon(foodMenu.getImage()), IMAGE_WIDTH, IMAGE_HEIGHT));


        description = new JTextArea();
        ComponentUtils.setTextAreaOnlyRead(description, this.getBackground());
        descContainer = new JScrollPane(description);
        descContainer.setPreferredSize(new Dimension(RIGHT_WIDTH, DESC_HEIGHT));

        DefaultListCellRenderer renderer = new DefaultListCellRenderer();
        renderer.setHorizontalAlignment(SwingConstants.CENTER);
        logList = new JList<>(defaultListModel);
        logList.setCellRenderer(renderer);
        logList.setFont(normalFont);
        logListContainer = new JScrollPane(logList);
        addBtn = new JButton("添加");
        updateBtn = new JButton("修改");
    }

    public void initParams(Map<String, Object> params) {
        if (params != null) {
            foodId = (String) params.get("id");
        }
        if (StringUtils.isNotBlank(foodId)) {
            // 请求菜单
            requestFood();
            // 请求日志次数
            requestLogCount();
        }

        initParams();
    }

    /**
     * 请求日志次数
     */
    private void requestLogCount() {
        Map<String, Object> requestParams = new HashMap<String, Object>() {{
            put("foodId", foodId);
        }};
        ResultVO<Integer> result = (ResultVO<Integer>) RequestUtils.sendRequest("log/count", requestParams);
        if (result.isSuccess()) {
            count = result.getData();
            defaultListModel = new DefaultListModel<>();
            for (int i = 0; i < count; i++) {
                defaultListModel.add(i, "第" + (i + 1) + "次");
            }
        } else {
            MessageUtils.showMessageDialog(this, result.getMessage(), "失败", JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * 请求菜单信息
     */
    private void requestFood() {
        Map<String, Object> requestParams = new HashMap<String, Object>() {{
            put("id", foodId);
        }};
        ResultVO<FoodMenu> result = (ResultVO<FoodMenu>) RequestUtils.sendRequest("food/get", requestParams);
        if (result.isSuccess()) {
            foodMenu = result.getData();
        } else {
            MessageUtils.showMessageDialog(this, result.getMessage(), "失败", JOptionPane.ERROR_MESSAGE);
        }
    }

    @Override
    public void initParams() {

    }

    @Override
    public void handleView() {
        Box leftVBox = Box.createVerticalBox();

        titleContainer.add(title);
        imageContainer.add(image);

        leftVBox.add(titleContainer);
        leftVBox.add(imageContainer);
        leftVBox.add(descContainer);

        leftPanel.add(leftVBox);

        rightPanel.add(logListContainer);
        JPanel btnPanel = new JPanel(new GridLayout(2, 1, 0, 0));
        btnPanel.add(addBtn);
        btnPanel.add(updateBtn);
        rightPanel.add(btnPanel, BorderLayout.SOUTH);

        this.add(outSplitPane);
    }

    @Override
    public void handleAction() {
        // 点击添加按钮事件
        addBtnClickEvent();
        // 点击修改按钮事件
        updateBtnClickEvent();
        // JList选择事件
        addLogListSelectedEvent();
    }

    /**
     * LogList 数据选择事件
     */
    private void addLogListSelectedEvent() {
        logList.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                String value = logList.getSelectedValue();
                int num = Integer.parseInt(value.substring(1, value.length() - 1));
                requestMenuLog(num);
            }
        });
    }

    /**
     * 请求菜单日志数据
     * @param num
     */
    public void requestMenuLog(int num) {
        Map<String, Object> requestParams = new HashMap<String, Object>() {{
            put("foodId", foodId);
            put("count", num);
        }};
        requestBegin();
        ResultVO<MenuLog> result = (ResultVO<MenuLog>) RequestUtils.sendRequest("log/getByCount", requestParams);
        if (result.isSuccess()) {
            menuLog = result.getData();
            reflushDataShow();
        } else {
            MessageUtils.showMessageDialog(this, result.getMessage(), "失败", JOptionPane.ERROR_MESSAGE);
        }
        requestEnd();
    }

    /**
     * 刷新数据显示
     */
    private void reflushDataShow() {
        image.setIcon(ImageUtils.scaleImage(new ImageIcon(menuLog.getImage()), IMAGE_WIDTH, IMAGE_HEIGHT));
        description.setText(menuLog.getDescription());
    }

    /**
     * 点击修改按钮事件
     */
    private void updateBtnClickEvent() {
        updateBtn.addActionListener(e -> {
            if (menuLog == null || StringUtils.isBlank(menuLog.getId())) {
                return;
            }
            Map<String, Object> params = new HashMap<String, Object>() {{
                put("id", menuLog.getId());
                put("foodId", foodId);
                put("parent", jd);
            }};
            RouterUtils.router(RouterConst.VIEW_ADDMENULOG, params);
        });
    }

    /**
     * 点击添加按钮事件
     */
    private void addBtnClickEvent() {
        addBtn.addActionListener(e -> {
            Map<String, Object> params = new HashMap<String, Object>() {{
                put("foodId", foodId);
                put("parent", jd);
            }};
            RouterUtils.router(RouterConst.VIEW_ADDMENULOG, params);
        });
    }

    /**
     * 添加次数
     */
    public void addCount() {
        defaultListModel.add(count, "第" + (count + 1) + "次");
        count++;
    }

    /**
     * 请求开始
     */
    private void requestBegin() {
        // 设置鼠标图标为加载图标
        this.setCursor(new Cursor(Cursor.WAIT_CURSOR));
        // 设置不能登录
        this.requestFlag = false;
    }

    /**
     * 请求结束
     */
    private void requestEnd() {
        // 还原鼠标图标
        this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        // 设置可以登录
        this.requestFlag = true;
    }

}
